package cn.iocoder.yudao.module.wms.service.bom;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.wms.controller.admin.bom.vo.BomPageReqVO;
import cn.iocoder.yudao.module.wms.controller.admin.bom.vo.BomRespVO;
import cn.iocoder.yudao.module.wms.controller.admin.bom.vo.BomSaveReqVO;
import cn.iocoder.yudao.module.wms.dal.dataobject.bom.BomDO;
import cn.iocoder.yudao.module.wms.dal.dataobject.bom.BomsDO;
import cn.iocoder.yudao.module.wms.dal.mysql.bom.BomMapper;
import cn.iocoder.yudao.module.wms.dal.mysql.bom.BomsMapper;
import cn.iocoder.yudao.module.wms.dal.redis.serialNumber.WmsSerialNumberRedisDAO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wms.enums.ErrorCodeConstants.BOM_NOT_EXISTS;

/**
 * BOM主 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class BomServiceImpl implements BomService {

    @Resource
    private BomMapper bomMapper;
    @Resource
    private BomsMapper bomsMapper;
    @Resource
    private WmsSerialNumberRedisDAO serialNumberRedisDAO;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createBom(BomSaveReqVO createReqVO) {
        // 插入
        BomDO bom = BeanUtils.toBean(createReqVO, BomDO.class);
        bomMapper.insert(bom);

        // 插入子表
        createBomsList(bom.getId(), createReqVO.getBomss());
        // 返回
        return bom.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBom(BomSaveReqVO updateReqVO) {
        // 校验存在
        validateBomExists(updateReqVO.getId());
        // 更新
        BomDO updateObj = BeanUtils.toBean(updateReqVO, BomDO.class);
        bomMapper.updateById(updateObj);

        // 更新子表
        updateBomsList(updateReqVO.getId(), updateReqVO.getBomss());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBom(Long id) {
        // 校验存在
        validateBomExists(id);
        // 删除
        bomMapper.deleteById(id);

        // 删除子表
        deleteBomsByOrderId(id);
    }

    private void validateBomExists(Long id) {
        if (bomMapper.selectById(id) == null) {
            throw exception(BOM_NOT_EXISTS);
        }
    }

    @Override
    public BomDO getBom(Long id) {
        return bomMapper.selectById(id);
    }

    @Override
    public PageResult<BomDO> getBomPage(BomPageReqVO pageReqVO) {
        return bomMapper.selectPage(pageReqVO, getCondition(pageReqVO.getCreator()));
    }

    @Override
    public PageResult<BomRespVO> selectJoinPage(BomPageReqVO pageReqVO) {
        return bomMapper.selectJoinPage(pageReqVO, getCondition(pageReqVO.getCreator()));
    }

    // ==================== 子表（BOM子） ====================

    @Override
    public List<BomsDO> getBomsListByByOrderId(Long orderId) {
        return bomsMapper.selectListByOrderId(orderId);
    }

    private void createBomsList(Long orderId, List<BomsDO> list) {
        list.forEach(o -> o.setOrderId(orderId));
        bomsMapper.insertBatch(list);
    }

    private void updateBomsList(Long orderId, List<BomsDO> list) {
        deleteBomsByOrderId(orderId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createBomsList(orderId, list);
    }

    private void deleteBomsByOrderId(Long orderId) {
        bomsMapper.deleteByOrderId(orderId);
    }

    /**
     * 去空转换
     * @param ids id
     * @return id集合
     */
    private Set<String> getCondition(String[] ids) {
        if (ids == null) {
            return Collections.emptySet();
        }
        return new HashSet<>(Arrays.asList(ids));
    }

}